package com.wangwei.authoritySystem.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig implements WebMvcConfigurer {
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;
    @Autowired
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;
    @Autowired
    private CustomerUserDetailsService customerUserDetailsService;
    @Autowired
    private CheckTokenFilter checkTokenFilter;
    //白名单
    private static  final String[] URL_WHITELIST = {
      "/login",
      "/logout",
      "/captcha",
      "/favicon.ico"
    };
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        //登录之前token过滤
        http.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //登录过程处理
        http.formLogin()  //表单登录
            .loginProcessingUrl("/api/user/login")//登录请求的url，自定义
            .successHandler(loginSuccessHandler) //认证成功处理器
            .failureHandler(loginFailureHandler) //认证失败处理器
            .and().csrf().disable() //跨域攻击
            //禁用session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            //拦截规则
            .and().authorizeRequests().antMatchers(URL_WHITELIST).permitAll()
            .anyRequest().authenticated() //其他请求一律需要认证拦截;
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(anonymousAuthenticationHandler) //匿名无权限访问
            .accessDeniedHandler(customerAccessDeniedHandler) //认证用户无权访问
            .and()
            .cors() //跨域
            .and().userDetailsService(customerUserDetailsService);
        return http.build();
    }
}

